library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;


entity ADDER is
generic (N : integer := 16);
port(	A 	  : in  std_logic_vector (N-1 downto 0);
		B 	  : in  std_logic_vector (N-1 downto 0);
		C_in : in  std_logic;
		SUB  : in  std_logic;
		OVF  : out std_logic;
		S 	  : out std_logic_vector (N-1 downto 0)
);
end ADDER;

architecture mixed of ADDER is
component RCA
generic(N : integer := 8);
port(	A_rca : in  std_logic_vector (N-1 downto 0);
		B_rca : in  std_logic_vector (N-1 downto 0);
		S_rca : out std_logic_vector (N-1 downto 0);
		C_i   : in  std_logic;
		C_o   : out std_logic
);
end component;

signal i_B 			: std_logic_vector (N-1 downto 0);
signal i_carry_i	: std_logic;
signal i_carry_o	: std_logic;
signal i_S 			: std_logic_vector (N-1 downto 0);
signal i_OVF 		: std_logic;
begin

contol_section: process (A,B,C_in,SUB,i_carry_o, i_S)
begin
-- SIGN=0,  A B unsigned
--  + OVF if A + B can't be stored in N bits
--  - OVF if B > A
	
	if SUB = '0' then		-- adder
		i_OVF 		<= i_carry_o;
		i_B 			<= B;
		i_carry_i 	<= C_in;
	else						-- subtracter
		i_B 			<= not B;
		i_carry_i 	<= '1';
		
		if B > A
		then
			i_OVF 	<= '1';
		else
			i_OVF 	<= '0';
		end if;
	end if;
	
end process;

RCA_core: RCA generic map(N) port
map ( A_rca => A,
		B_rca => i_B,
		S_rca => i_S,
		C_i	=> i_carry_i,
		C_o	=> i_carry_o
);

S 		<= i_S;
OVF 	<= i_OVF;

end mixed;

